#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>

#include "../comm/util.hpp"
#include "../comm/logger.hpp"

using namespace ns_util;
namespace ns_runner
{
    class runner
    {
    public:
        runner() {}
        ~runner() {}
        //设置资源占用
        static void SetProcLimit(int _cpu_limit, int _mem_limit)
        {
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_cur = _cpu_limit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_CPU, &cpu_rlimit);

            struct rlimit mem_rlimit;
            mem_rlimit.rlim_cur = _mem_limit * 1024; //转换成KB
            mem_rlimit.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_AS, &mem_rlimit);
        }
        /*
        返回值：>0 程序异常，返回值为退出信号
               <0 内部错误
               ==0 执行成功
        */
        static int Run(const std::string &fileName, int _cpu_limit, int _mem_limit)
        {
            /*
                不考虑运行结果是否正确
                只考虑是否成功运行
            */
            std::string _execute = PathUtil::Exe(fileName);
            std::string _stdin = PathUtil::Stdin(fileName);
            std::string _stdout = PathUtil::Stdout(fileName);
            std::string _stderr = PathUtil::Stderr(fileName);

            umask(0);
            int _stdin_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int _stdout_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int _stderr_fd = open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);

            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                LOG(DEBUG, "文件打开失败\n");
                if (_stdin_fd > 0)
                    close(_stdin_fd);
                if (_stdout_fd > 0)
                    close(_stdin_fd);
                if (_stderr_fd > 0)
                    close(_stderr_fd);
                return -1;
            }

            pid_t pid = fork();
            if (pid < 0)
            {
                close(_stdin_fd);
                close(_stdin_fd);
                close(_stderr_fd);
                LOG(DEBUG, "运行时创建子进程失败\n");
                return -2;
            }
            else if (pid == 0)
            {
                SetProcLimit(_cpu_limit,_mem_limit);
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);

                execlp(_execute.c_str(), _execute.c_str(), nullptr);

                exit(1);
            }
            else
            {
                int status = 0;
                waitpid(pid, &status, 0);
                close(_stdin_fd);
                close(_stdin_fd);
                close(_stderr_fd);
                // 程序异常会返回信号
                LOG(INFO, "程序执行完毕 info: %d\n", status & 0x7F);
                return status & 0x7F;
            }
        }
    };
};